import siteAPI from '@/apis/site';
import iconApi from '@/apis/iconApi.js';
import { getServerImgUrl } from '@/utils/util.js';
import { mapState } from 'vuex';
import { $demoi18n } from '@/utils/lang';

const errorMap = {
  100014: $demoi18n('iconUpload.filenameErr'),
  70002: $demoi18n('iconUpload.tooBigErr'),
  70001: $demoi18n('iconUpload.extErr'),
  100108: $demoi18n('icon-upload-mixin.uploadMaxNumErr'), // 图片库分类下图片数量超过限制
};

export default {
  props: {
    widgetInstanceId: String,
  },
  inject: {
    panelWid: {
      default: '',
    },
  },
  computed: {
    ...mapState({
      panelConfigs: state => state.VisualComponentsModule.panelConfigs,
    }),
  },

  methods: {
    getSuccessRes(res) {
      let imgId = '';
      let imgUrl = '';
      let message = '';
      let isSuccess = false;
      if (res.data) {
        message = res.data.message;
        if (res.data.code === 200) {
          imgId = res.data.data;
          imgUrl = getServerImgUrl(imgId, 'xvue', true);
          isSuccess = true;
        }
      }
      const result = {
        isSuccess,
        imgId,
        imgUrl,
        message,
        response: {
          data: res.data,
        },
      };
      return result;
    },

    getFailRes(res) {
      const result = {
        isSuccess: false,
        imgId: '',
        imgUrl: '',
        message: $demoi18n('iconUpload.failedToUploadTheImage'),
        ...res,
      };
      return result;
    },

    /**
     * 有些浏览器(如edge)不支持new File，所以为了兼容，base64要先转换成blob再设置type，name，lastModifiedDate
     * 属性间接转换成文件，而不推荐直接new File()的方式
     *
     */
    convertBase64UrlToImgFile(urlData, fileName, fileType) {
      const arr = urlData.split(','); // 取arr[1], base64编码,不包含头部部分：data:img/jpg;base64
      const bytes = window.atob(arr[1]); // 转换为byte
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length);
      const ia = new Int8Array(ab);
      let i;
      for (i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }

      // 转换成文件，添加文件的type，name，lastModifiedDate属性
      const blob = new Blob([ab], { type: fileType });
      blob.lastModifiedDate = new Date();
      blob.name = fileName;
      return blob;
    },

    /**
     * 上传blob图片
     * @param  {String} file 图片源码
     * @param  {Number} type 图片操作类型
     *                         1: 组件图，
     *                         2: 页面背景图，
     *                         5: 使用图片库
     *                         6: 上传图片但不记录到图片库
     * @param  {String} cateId 分类id
     * @return {Object}      上传结果
     */
    uploadImageData({ file, type = 1, cateId = '' }) {
      return new Promise(resolve => {
        const formData = new FormData();

        let ext = 'png';
        if (file.name) {
          ext = file.name.split('.').pop().toLowerCase();
          const allowExts = ['jpg', 'jpeg', 'png', 'gif'];
          if (!allowExts.includes(ext)) {
            const res = this.getFailRes({ isSuccess: false, errCode: 70001, message: errorMap[70001] });
            resolve(res);
            return;
          }
        } else if (file.type) {
          const extMap = { 'image/png': 'png', 'image/jpeg': 'jpg' };
          if (extMap[file.type]) {
            ext = extMap[file.type];
          }
        } else {}

        const filename = `${new Date().getTime()}.${ext}`;
        formData.append('multipartFile', file, filename);

        if (cateId) {
          formData.append('libraryId', cateId);
          this.uploadImgToCate(formData).then(res => {
            resolve(res);
          });
        } else {
          formData.append('type', type);
          this.uploadImgToCustom(formData).then(res => {
            resolve(res);
          });
        }
      });
    },

    // 使用旧接口上传到未分类
    uploadImgToCustom(formData) {
      return new Promise(resolve => {
        let { siteId, widgetInstanceId } = this.panelConfigs[this.panelWid] || {};
        widgetInstanceId = widgetInstanceId.replace(/_child.*$/, '');

        // 本地环境，需要先获取远程环境的token才能用
        if (process.env.NODE_ENV === 'development') {
          siteId = window.pageInfo.moduleList[0].siteUuid;
          widgetInstanceId = window.pageInfo.moduleList[0].uuid;
        }

        siteAPI
          .xvueIconUpload(formData, siteId, widgetInstanceId)
          .then(result => {
            const res = this.getSuccessRes(result);
            resolve(res);
          })
          .catch(err => {
            let res = {};
            const errData = err?.response?.data;
            if (errData) {
              const { code } = errData;
              if (errorMap[code]) {
                res.message = errorMap[code];
              } else {
                res.message = errorMap.message || $demoi18n('iconUpload.failedToUploadTheImage');
              }
              res.errCode = code;
            }
            res = this.getFailRes(res);
            resolve(res);
          });
      });
    },

    // 使用新接口上传到图片库分类
    uploadImgToCate(formData) {
      return new Promise(resolve => {
        iconApi
          .uploadImgToCate(formData)
          .then(result => {
            const res = this.getSuccessRes(result);
            if (res.isSuccess) {
              resolve(res);
            } else {
              throw res;
            }
          })
          .catch(err => {
            let res = {};
            const errData = err?.response?.data;
            if (errData) {
              const { code: _code } = errData;
              if (errorMap[_code]) {
                res.message = errorMap[_code];
              } else {
                res.message = errorMap.message || $demoi18n('iconUpload.failedToUploadTheImage');
              }
              res.errCode = _code;
            }
            res = this.getFailRes(res);
            resolve(res);
          });
      });
    },

  },
};
